#!/bin/bash
# ---------------------------------------------------------------------------
# Build wxWidgets and wxPython on a OSX box.  This is normally called
# remotely from build-all but it should be able to be used standalone
# too...
# 
# The command line must have the following parameters:
#
#    1. the path to the base of the wx source tree
#    2. the path of where to put the resulting installers
#    3. skipclean flag (yes|no)
#    4. the VERSION
#    5. the version of Python to build for
#    6. the character type (ansi|unicode|both)
#
# ---------------------------------------------------------------------------

set -o errexit
#set -o xtrace

echo "-=-=-=-  Hello from $HOSTNAME  -=-=-=-"

if [ $# -lt 6 ]; then
    echo "Usage: $0 WXDIR DESTDIR SKIPCLEAN VERSION PYVER [carbon|cocoa]"
    exit 1
fi

WXDIR=$1
DESTDIR=$2
SKIPCLEAN=$3
VERSION=$4
PYVER=$5
PORT=$6


export PATH=/sw/bin:/sw/sbin:/mp/bin:/usr/local/bin:/bin:/sbin:/usr/bin:/usr/sbin:.:/usr/X11R6/bin

# untar the source 
echo "Unarchiving wxPython-src-$VERSION.tar.bz2"
cd $DESTDIR
tar xjf wxPython-src-$VERSION.tar.bz2
rm wxPython-src-$VERSION.tar.bz2


cd $WXDIR/wxPython
export TARBALLDIR=$DESTDIR
mkdir -p dist


#----------------------------------------------------------------------
# Do a universal build of wxWidgets and wxPython.  This is a
# simplified version of parts of the old distrib/mac/wxPythonOSX/build 
# script.

OSX_VERSION=`sw_vers -productVersion`
OSX_VERSION=${OSX_VERSION:0:4}
if [ "$PORT" = "cocoa" ]; then
    PORTFLAG="--osx_cocoa"
else
    PORTFLAG="--osx_carbon"
fi
PYTHON=python$PYVER
PYTHONW=pythonw$PYVER
SHORTVER=${VERSION:0:3}
#PYPREFIX=`$PYTHON -c "import sys; print sys.exec_prefix"`
#PYLIB=$PYPREFIX/lib/python$PYVER
PYSYSEXE=`$PYTHON -c "import sys; print sys.executable"`


TARBALL=$TARBALLDIR/wxPython-src-$VERSION.tar.bz2

if [ ! -e $TARBALLDIR/wxPython-demo-$VERSION.tar.bz2 ]; then 
    echo "-------------------------------------------------------"
    echo " WARNING:  Demo tarball not found, will skip building "
    echo "           the Demo app bundle and etc."
    echo " $TARBALLDIR/wxPython-demo-$VERSION.tar.bz2"
    echo "-------------------------------------------------------"
fi

if [ ! -e $TARBALLDIR/wxPython-docs-$VERSION.tar.bz2 ]; then
    echo "-------------------------------------------------------"
    echo " WARNING:  Docs tarball not found, will skip building "
    echo "           the the wxDocsViewer app bundle and etc."
    echo " $TARBALLDIR/wxPython-docs-$VERSION.tar.bz2"
    echo "-------------------------------------------------------"
fi



function my_makedmg {
    DMGROOTDIR=$1
    DMGDIR=$2
    dmgname=$3
    echo my_makedmg $DMGROOTDIR $DMGDIR $dmgname
    hdiutil create -format UDZO -volname $dmgname -imagekey zlib-level=9 \
                   -srcfolder $DMGROOTDIR   $DMGDIR/$dmgname.dmg
}


function do_universal_build {

    PYUNICODEOPT="--unicode"
    
    PREFIX=/usr/local/lib/wxPython-$VERSION
    PREFIX_LINK=/usr/local/lib/wxPython
    SITEPACKAGES=$PREFIX/lib/python$PYVER/site-packages
    BINPREFIX=/usr/local/bin
    WXROOT=$WXDIR
    ##TMPDIR=$DESTDIR/_build_
    TMPDIR=$DESTDIR
    BUILDROOT=$TMPDIR/bld
    INSTALLROOT=$TMPDIR/install-root
    INSTALLAPPS=$TMPDIR/install-apps

    DMGDIR=$TMPDIR/dmg
    DMGROOT=$DMGDIR/root
    DMGAPPS=$DMGDIR/apps

    PROGDIR=$WXDIR/wxPython/distrib/mac
    RESOURCEDIR=$PROGDIR/resources


    # Setup build dirs
    mkdir -p $BUILDROOT
    mkdir -p $INSTALLROOT
    mkdir -p $INSTALLAPPS

    rm -rf $DMGDIR
    mkdir -p $DMGROOT
    mkdir -p $DMGAPPS/Docs
    mkdir -p $DMGAPPS/Samples

    pushd $BUILDROOT

    # Call the new fangled handy dandy build script to build both
    # wxWidgets and wxPython.
    pushd $WXROOT/wxPython
    echo $PYTHON -u ./build-wxpython.py \
	$PYUNICODEOPT \
	--mac_universal_binary $PORTFLAG \
	--build_dir=$BUILDROOT \
	--install \
	--prefix=$PREFIX \
	--installdir=$INSTALLROOT \
        --wxpy_installdir=$INSTALLROOT$PREFIX

    $PYTHON -u ./build-wxpython.py \
	$PYUNICODEOPT \
	--mac_universal_binary $PORTFLAG \
	--build_dir=$BUILDROOT \
	--install \
	--prefix=$PREFIX \
	--installdir=$INSTALLROOT \
        --wxpy_installdir=$INSTALLROOT$PREFIX

    popd



    PKGDIR=`cat $INSTALLROOT$SITEPACKAGES/wx.pth`
    rm $INSTALLROOT$SITEPACKAGES/wx.pth
    cd $WXROOT/wxPython
    cp distrib/wxhack.py $INSTALLROOT$SITEPACKAGES/..
    cat > $INSTALLROOT$SITEPACKAGES/../wxhack.pth <<EOF
site-packages
site-packages/$PKGDIR
# Move these new paths from the end of the list up to before the stock 
# paths, but after any PYTHONPATH settings.
import wxhack; wxhack.fixpath('$PYVER', 2)
EOF

    # install wxPython's tool scripts
    mkdir -p $INSTALLROOT$BINPREFIX
    cd $WXROOT/wxPython/scripts
    $PYTHON CreateMacScripts.py $INSTALLROOT $BINPREFIX


    # Remove the .pyc/.pyo files, they just take up space and can be recreated
    # during the install.
    pushd $WXROOT/wxPython
    $PYTHON $WXROOT/wxPython/distrib/mac/zappycfiles.py $INSTALLROOT > /dev/null
    popd

    # Set premissions for files in $INSTALLROOT
    if [ "$UID" = "0" ]; then
        chown -R root:admin $INSTALLROOT
        chmod -R g+w        $INSTALLROOT
    fi



    #-----------------------------------------------------------------
    # Make the Installer package and disk image

    # first some resource files
    cat > $RESOURCEDIR/Welcome.txt <<EOF
Welcome!

This Installer package will install the wxPython runtime $VERSION for the Universal version of MacPython $PYVER.  This includes:

    * The wxPython extension modules and library packages
    * The wxWidgets shared libraries and headers
    * Some command line tool scripts, installed to /usr/local/bin.

You must install onto your current boot disk, even though the installer does not enforce this, otherwise things will not work.

You can install more than one version of the wxPython runtime if you desire.  The most recently installed version will be the default wxPython, but you can choose another by setting the PYTHONPATH or by using the wxversion module.  See http://wiki.wxpython.org/index.cgi/MultiVersionInstalls for more details.

Build date:   `date`
EOF

    # make the preflight script
    cat > $RESOURCEDIR/preflight <<EOF
#!/bin/sh
# Cleanup any old install of the wxPython package
rm -rf \$2$SITEPACKAGES/wxPython
rm -rf \$2$SITEPACKAGES/wx
rm -rf \$2$SITEPACKAGES/$PKGDIR
exit 0
EOF
    chmod +x $RESOURCEDIR/preflight

    # make the postflight script
    cat > $RESOURCEDIR/postflight <<EOF
#!/bin/sh -e

# Make a link to the newest install of wxMac/wxPython
rm -f $PREFIX_LINK
ln -s `basename $PREFIX` $PREFIX_LINK
 
# find a Python $PYVER binary
for dir in /usr/bin \
           /usr/local/bin \
           /Library/Frameworks/Python.framework/Versions/$PYVER/bin \
           /System/Library/Frameworks/Python.framework/Versions/$PYVER/bin; do 
    if [ -e \$dir/python$PYVER ]; then
	PYTHON=\$dir/python$PYVER
	break
    fi
done

if [ -z \$PYTHON ]; then
    echo ERROR: Unable to find a Python $PYVER binary
    exit 1
fi

# Byte-compile the .py files to .pyc and .pyo
\$PYTHON    -m compileall \$2$SITEPACKAGES/$PKGDIR
\$PYTHON -O -m compileall \$2$SITEPACKAGES/$PKGDIR

# and all of the wxPython package should be group writable
chgrp -R admin \$2$SITEPACKAGES/$PKGDIR
chmod -R g+w \$2$SITEPACKAGES/$PKGDIR

# install a .pth file in any Python $PYVER installs we can find
for dir in /Library/Python/$PYVER/site-packages \
           /Library/Frameworks/Python.framework/Versions/$PYVER/lib/python$PYVER/site-packages; do
    if [ -d \$dir ]; then
        echo Writing wxredirect.pth in \$dir
        DEST=\`dirname $SITEPACKAGES\`
        cat > \$dir/wxredirect.pth <<pthEOF
import site; site.addsitedir('\$DEST')
pthEOF
    fi
done

EOF


cat >> $RESOURCEDIR/postflight <<EOF
exit 0
EOF
    chmod +x $RESOURCEDIR/postflight



    # Build the main Installer Package...
    PKGNAME=wxPython${SHORTVER}-osx-$PORT-py$PYVER
    rm -rf $PKGNAME.pkg
    $PYTHON $PROGDIR/buildpkg.py \
        --Title=$PKGNAME \
        --Version=$VERSION \
        --Description="wxPython runtime $VERSION for the Universal version of MacPython $PYVER" \
        --NeedsAuthorization="YES" \
        --Relocatable="NO" \
        --InstallOnly="YES" \
        $INSTALLROOT \
        $RESOURCEDIR

    mv $PKGNAME.pkg $DMGROOT/$PKGNAME.pkg

    rm $RESOURCEDIR/postflight
    rm $RESOURCEDIR/preflight
    rm $RESOURCEDIR/Welcome.txt


    cat > "$DMGROOT/README 1st.txt" <<EOF
Welcome to wxPython!

This disk image contains the following items:

    wxPython${SHORTVER}-osx-$VERSION-$PORT

        This Installer contains the wxPython runtime version $VERSION.
        It includes all the Python modules and extension modules for
        wxPython, as well as the wxWidgets libraries.

        It is possible to have more than one version of the runtime
        installed at once if you wish.  The most recently installed
        version will be the default wxPython, but you can choose
        another by setting the PYTHONPATH or by using the wxversion
        module.  For more details see:
        http://wiki.wxpython.org/index.cgi/MultiVersionInstalls 


    uninstall_wxPython.py

        A simple tool to help you manage your installed versions of
        wxPython.  It will allow you to choose from the currently
        installed wxPython packages and to select one for
        uninstallation.  It is a text-mode tool so you can either run
        it from a Terminal command line, or you can open it with
        PythonLauncher and let it create a Terminal to run it in.

        NOTE: If you have versions prior to 2.5.3.1 installed, please
        do run this uninstall tool to remove the older version.

EOF


    cp $PROGDIR/uninstall_wxPython.py $DMGROOT

    # Make a disk image to hold these files
    dmgname=wxPython${SHORTVER}-osx-$VERSION-$PORT-py$PYVER
    #$PROGDIR/makedmg $DMGROOT $DMGDIR $dmgname
    my_makedmg $DMGROOT $DMGDIR $dmgname


    echo Moving $DMGDIR/$dmgname.dmg to $DESTDIR
    mv $DMGDIR/$dmgname.dmg  $DESTDIR/$dmgname.dmg



    #-----------------------------------------------------------------
    # Now create app bundles for the demo, docs, and tools and make
    # another disk image to hold it all.

    cat > "$DMGAPPS/README 1st.txt" <<EOF
Welcome to wxPython!

On this disk image you will find Demo, Tools, Docs, and etc. for
wxPython $VERSION.  

Everything here is optional and you can drag them out of the disk
image and drop them wherever you want.  You will need to have an
installed wxPython runtime to be able to use any of them.


   wxPython Demo        An application bundle version of the demo.
                        (This has it's own copy of the demo sources 
                        within the bundle so you can move the whole 
                        bundle around as needed.)

   XRCed                An application for editing wxPython resource
                        files  (XRC files.)

   PyCrust              An application that provides an interactive
                        Python shell and also namespace inspectors.

   PySlices             An enhanced version of PyCrust that allows
                        multi-line commands in an interface like 
                        Sage or Mathematica.

   Editra               A simple yet powerful programmer's editor.


   Docs/wxDocsViewer    An application that allows you to view the
                        wxWidgets documentation.

   Docs/licence         License files.

   Docs/other           A few readmes, change log, etc.


   Samples/samples      Several small sample applications that
                        demonstrate how to use wxPython.

   Samples/demo         A copy of the wxPython demo source code,
                        just open the folder and run demo.pyw.

Happy Hacking!
EOF


    # wxDocs
    if [ ! -e $TARBALLDIR/wxPython-docs-$VERSION.tar.bz2 ]; then
        cat > "$DMGAPPS/Docs/Build ERROR.txt" <<EOF

The wxPython-docs tarball was not found when building this disk image!

EOF

    else
        pushd $BUILDROOT
        tar xjvf $TARBALLDIR/wxPython-docs-$VERSION.tar.bz2
        popd

        ## Make an app to launch viewdocs.py
        #$PYTHONW $PROGDIR/buildapp.py \
        #    --builddir=$DMGAPPS/Docs \
        #    --name=wxDocsViewer \
        #    --mainprogram=$BUILDROOT/wxPython-$VERSION/docs/viewdocs.py \
        #    --iconfile=$PROGDIR/Info.icns \
	#    --python=/usr/bin/python \
	#    --executable=$PYSYSEXE \
        #    build
        #
        #cp $BUILDROOT/wxPython-$VERSION/docs/*.zip $DMGAPPS/Docs/wxDocsViewer.app/Contents/Resources


	# Until the DocsViewer app is working again just copy the html files
	mv $BUILDROOT/wxPython-$VERSION/docs/wx $DMGAPPS/Docs
 

        cat > "$DMGAPPS/Docs/README 1st.txt" <<EOF

The wxDocsViewer application needs to be copied to your Desktop (or
someplace else you have write access to) before you can run it, so it
can cache some indexes within its bundle.

EOF

    fi

    # license files, docs, etc.
    pushd $DMGAPPS/Docs
    cp -pR $WXDIR/wxPython/licence   .
    cp -pR $WXDIR/wxPython/docs      .
    rm -rf docs/bin
    rm -rf docs/xml-raw
    mv docs other
    popd


    if [ ! -e $TARBALLDIR/wxPython-demo-$VERSION.tar.bz2 ]; then
        cat > "$DMGAPPS/Samples/Build ERROR.txt" <<EOF

The wxPython-$VERSION-demo tarball was not found when building this disk image!

EOF
        cp "$DMGAPPS/Samples/Build ERROR.txt" $DMGAPPS

    else

        # Copy the demo and samples to the disk image from the tarball
        pushd $DMGAPPS/Samples
        tar xjvf $TARBALLDIR/wxPython-demo-$VERSION.tar.bz2
        mv wxPython-$VERSION/* .
        rm -rf wxPython-$VERSION
        rm -f demo/b demo/.setup.sh
        mv demo/demo.py demo/demo.pyw
        popd

        # Make an app bundle to run the demo
        $PYTHONW $PROGDIR/buildapp.py \
            --builddir=$DMGAPPS \
            --name="wxPython Demo" \
            --mainprogram=$DMGAPPS/Samples/demo/demo.pyw \
            --iconfile=$PROGDIR/RunDemo.icns \
	    --python=/usr/bin/python \
	    --executable=$PYSYSEXE \
            build
        cp -pR $DMGAPPS/Samples/demo/* "$DMGAPPS/wxPython Demo.app/Contents/Resources"
    fi


    # Make an app bundle to launch PyCrust
    $PYTHONW $PROGDIR/buildapp.py \
        --builddir=$DMGAPPS \
        --name=PyCrust \
        --mainprogram=$INSTALLROOT$BINPREFIX/pycrust.py \
        --iconfile=$PROGDIR/PieShell.icns \
	--python=/usr/bin/python \
	--executable=$PYSYSEXE \
        build


    # Make an app bundle to launch PySlices
    $PYTHONW $PROGDIR/buildapp.py \
        --builddir=$DMGAPPS \
        --name=PySlices \
        --mainprogram=$INSTALLROOT$BINPREFIX/pyslices.py \
        --iconfile=$PROGDIR/PieShell.icns \
	--python=/usr/bin/python \
	--executable=$PYSYSEXE \
        build


    # Make an app to launch XRCed
    $PYTHONW $PROGDIR/buildapp.py \
        --builddir=$DMGAPPS \
        --name=XRCed \
        --mainprogram=$INSTALLROOT$BINPREFIX/xrced.py \
        --iconfile=$WXDIR/wxPython/wx/tools/XRCed/XRCed.icns \
	--argv \
	--python=/usr/bin/python \
	--executable=$PYSYSEXE \
        build


    # Make an app to launch Editra
    $PYTHONW $PROGDIR/buildapp.py \
        --builddir=$DMGAPPS \
        --name=Editra \
        --mainprogram=$INSTALLROOT$BINPREFIX/editra.py \
        --iconfile=$WXDIR/wxPython/wx/tools/Editra/pixmaps/Editra.icns \
	--resource=$WXDIR/wxPython/wx/tools/Editra/pixmaps/editra_doc.icns \
	--argv \
	--python=/usr/bin/python \
	--executable=$PYSYSEXE \
        build
    PYTHONPATH=$WXDIR/wxPython/wx/tools \
        $PYTHONW $PROGDIR/updateEditraPlist.py $DMGAPPS/Editra.app/Contents/Info.plist


    # and then finally make a disk image containing everything
    dmgname=wxPython${SHORTVER}-osx-docs-demos-$VERSION-$PORT-py$PYVER
    #$PROGDIR/makedmg $DMGAPPS $DMGDIR $dmgname
    my_makedmg $DMGAPPS $DMGDIR $dmgname

    echo Moving $DMGDIR/$dmgname.dmg to $DESTDIR
    mv $DMGDIR/$dmgname.dmg  $DESTDIR/$dmgname.dmg

}


do_universal_build



#----------------------------------------------------------------------

if [ $SKIPCLEAN != yes ]; then 
    echo "Cleaning up..."
    cd $DESTDIR
    rm -rf $BUILDROOT || true
    rm -rf $INSTALLROOT || true
    rm -rf $INSTALLAPPS || true
    rm -rf $DMGDIR || true
    rm -r $WXDIR || true
    rm wxPython-docs-$VERSION.tar.bz2 || true
    rm wxPython-demo-$VERSION.tar.bz2 || true
fi

echo "-=-=-=-  Goodbye!  -=-=-=-"
